﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using WpfApp.Tools.Utils;

namespace WpfApp.View.SystemInformation
{
    /// <summary>
    /// WD_UpdateStaffInformation.xaml 的交互逻辑
    /// </summary>
    public partial class WD_UpdateStaffInformation : Window
    {
        DataRowView DGVR;//接收一行数据
        string myPictureByte;//接收图片路径
        List<string> lisWenJianMing = new List<string>();
        List<byte[]> lstBytes = new List<byte[]>();
        //保存旧图片
        string strOldLuJing;
        int intFid;
        BLL.UCStaffInformation.UC_StaffInformationClient myStaff = new BLL.UCStaffInformation.UC_StaffInformationClient();
        public WD_UpdateStaffInformation(DataRowView drv)
        {
            InitializeComponent();
            DGVR = drv;
        }
        /// <summary>
        /// 页面加载时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            #region 绑定下拉框
            //查询性别
            DataTable dt = myStaff.SelectGender().Tables[0];
            cbo_gender.ItemsSource = dt.DefaultView;
            cbo_gender.DisplayMemberPath = "GenderName";
            cbo_gender.SelectedValuePath = "GenderId";
            //查询工作状态
            DataTable dtWorkStatus = myStaff.SelectWorkStatus().Tables[0];
            cbo_Work.ItemsSource = dtWorkStatus.DefaultView;
            cbo_Work.DisplayMemberPath = "WorkStatusName";
            cbo_Work.SelectedValuePath = "WorkStatusId";
            //查询职务
            DataTable dtPost = myStaff.SelectPost().Tables[0];
            cbo_Post.ItemsSource = dtPost.DefaultView;
            cbo_Post.DisplayMemberPath = "PostName";
            cbo_Post.SelectedValuePath = "PostId";
            #endregion
            //1.1页面数据回填
            txt_Number.Text = (DGVR.Row["staffNumber"]).ToString();
            txt_Name.Text = (DGVR.Row["staffName"]).ToString();
            cbo_Post.SelectedValue = Convert.ToInt32(DGVR.Row["as_BranchID"]);
            txt_PhoneNumber.Text = (DGVR.Row["phoneNumber"]).ToString();
            cbo_Work.SelectedValue = Convert.ToInt32(DGVR.Row["as_WorkStatusID"]);
            cbo_gender.SelectedValue = Convert.ToInt32(DGVR.Row["as_GenderID"]);
            txt_idCar.Text = (DGVR.Row["idCard"]).ToString();
            dtp_Birthday.Text = (DGVR.Row["dateOfBirth"]).ToString();
            txt_Age.Text = (DGVR.Row["staffAge"]).ToString();
            txt_Address.Text = (DGVR.Row["staffAddress"]).ToString();
            txt_Email.Text = (DGVR.Row["eMail"]).ToString();
            dtp_EnterDate.Text = (DGVR.Row["entryDate"]).ToString();
            dtp_LeaveDate.Text = (DGVR.Row["departureDate"]).ToString();
            if (DGVR.Row["operatorOrNot"].ToString() == "操作员")
            {
                chk_operator.IsChecked = true;
            }
            txt_Note.Text = (DGVR.Row["note"]).ToString();
            txt_Load.Text = (DGVR.Row["staffPicture"]).ToString();
            #region 显示图片
            strOldLuJing = (DGVR.Row["staffPicture"]).ToString();
            //获取文件路径（物理路径）
            myPictureByte = myStaff.SelectPhoro(strOldLuJing);
            if (myPictureByte != null)
            {
                try
                {
                    BitmapImage bi = new BitmapImage();
                    bi.BeginInit();
                    bi.CacheOption = BitmapCacheOption.OnLoad;
                    bi.UriSource = new Uri(myPictureByte);
                    bi.EndInit();
                    //获取内存图片
                    img_photo.Source = bi;
                }
                catch (Exception)
                {
                    img_photo.Source = null;
                }
            }

            #endregion

        }
        /// <summary>
        /// 部门下拉框改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbo_Post_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                //获取职务
                if (Convert.ToInt32(cbo_Post.SelectedValue) != 0)
                {
                    intFid = Convert.ToInt32(cbo_Post.SelectedValue);
                }
                else
                {
                    intFid = Convert.ToInt32(DGVR.Row["PostId"]);
                }
                DataTable dt = myStaff.SelectEmployeeType(intFid).Tables[0];
                cbo_StaffType.ItemsSource = dt.DefaultView;
                cbo_StaffType.DisplayMemberPath = "EmployeeTypeName";
                cbo_StaffType.SelectedValuePath = "EmployeeTypeId";
                cbo_StaffType.SelectedValue = Convert.ToInt32(DGVR.Row["as_EmployeeTypeID"]);
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 修改保存按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //第一步：判断页面数据
                if (cbo_gender.SelectedValue != null && cbo_Post.SelectedValue !=null&& cbo_StaffType.SelectedValue!= null
               && cbo_Work.SelectedValue != null && txt_Address.Text != "" && txt_Age.Text != "" && txt_Email.Text != ""
               && txt_idCar.Text != "" && txt_Name.Text != "" && txt_Note.Text != "" &&
               txt_Number.Text != "" && txt_PhoneNumber.Text != "" && dtp_Birthday.Text.ToString() != "" &&
               dtp_EnterDate.Text.ToString() != "")
                {
                    //第二步：获取页面数据
                    int intas_employee_type_id = Convert.ToInt32(cbo_StaffType.SelectedValue);
                    int intas_work_status_id = Convert.ToInt32(cbo_Work.SelectedValue);
                    int intas_branch_id = Convert.ToInt32(cbo_Post.SelectedValue);
                    string strstaff_name = txt_Name.Text.ToString();
                    string strstaff_number = txt_Number.Text.ToString();
                    int intas_gender_id = Convert.ToInt32(cbo_gender.SelectedValue);
                    string strage = txt_Age.Text.ToString();
                    string strid_card = txt_idCar.Text.ToString();
                    DateTime dtmbirth = Convert.ToDateTime(dtp_Birthday.Text.ToString());
                    string strphone_number = txt_PhoneNumber.Text.ToString();
                    string straddress = txt_Address.Text.ToString();
                    string stre_mail = txt_Email.Text.ToString();
                    DateTime dtmentry_date = Convert.ToDateTime(dtp_EnterDate.Text.ToString());
                    DateTime dtmdeparture_date = Convert.ToDateTime(dtp_LeaveDate.Text.ToString());
                    bool bloperator_no = (bool)chk_operator.IsChecked;//获取checkbox
                    string strnote = txt_Note.Text.ToString();
                    int staffID = Convert.ToInt32(DGVR.Row["staffID"]);
                    string strTxtLuJing = txt_Load.Text.ToString().Trim();
                    byte[][] byteWenJian = new byte[lstBytes.Count][];
                    for (int i = 0; i < lstBytes.Count; i++)
                    {
                        byteWenJian[i] = lstBytes[i];
                    }
                    //第三步：调用服务器保存方法
                    int count = myStaff.UpdateStaffInformation(intas_employee_type_id, intas_work_status_id, intas_branch_id, strstaff_name, strstaff_number, intas_gender_id, strage, strid_card,
                   dtmbirth, strphone_number, straddress, stre_mail, dtmentry_date, dtmdeparture_date, bloperator_no, byteWenJian, strnote, staffID, strOldLuJing, strTxtLuJing);
                    //第四步：根据保存情况做提示
                    if (count > 0)
                    {
                        MessageBoxResult dr = MessageBox.Show("修改【" + strstaff_number + "】员工信息！", "系统提示", MessageBoxButton.OKCancel, MessageBoxImage.Information);//弹出确定对话框
                        this.Close();
                    }
                    else if (count == -1)
                    {
                        MessageBox.Show("修改员工信息重复！");
                    }
                }
                else
                {
                    MessageBox.Show("请检查是否存在空数据。");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {

        }

       
        /// <summary>
        /// 验证电话号码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txt_PhoneNumber_TextChanged(object sender, TextChangedEventArgs e)
        {
            string strPhoneNumber = txt_PhoneNumber.Text.Trim();
            if (strPhoneNumber != "")
            {
                if (strPhoneNumber.Length == 11)
                {
                    if (Tools.Utils.CheckTrueOrFalse.checkPhone(strPhoneNumber) == false)
                    {
                        MessageBox.Show("手机号格式不对，请重新输入！", "系统提示", MessageBoxButton.OKCancel, MessageBoxImage.Error);
                        //清空文本
                        txt_PhoneNumber.Text = string.Empty;
                    }
                }
                else if (strPhoneNumber.Length < 11)
                {
                    MessageBox.Show("手机号格式不对或者输入的号码没有11位，请重新输入！", "系统提示", MessageBoxButton.OKCancel, MessageBoxImage.Error);
                }
            }
            else
            {
                strPhoneNumber = null;
            }
            
        }
        /// <summary>
        /// 验证身份证号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txt_idCar_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (txt_idCar.Text.ToString().Length == 6)
            {

                string strAddress = CheckIDCardGetDiQu.LoadAddress(txt_idCar.Text.ToString());
                if (strAddress == "")
                {
                    MessageBox.Show("身份证不合法！");
                }
                else
                {
                    txt_Address.Text = strAddress;
                }
            }
            if (txt_idCar.Text.ToString().Length < 6)
            {
                txt_Address.Text = "";
            }
        }
        /// <summary>
        /// 选择图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Open_Click(object sender, RoutedEventArgs e)
        {
            Stream photo = null;
            int length;
            OpenFileDialog ofdWenJian = new OpenFileDialog();
            //允许获取获取多张图片
            ofdWenJian.Multiselect = true;
            ofdWenJian.Filter = "ALL Image Files|*.*";
            if ((bool)ofdWenJian.ShowDialog())
            {
                if ((photo = ofdWenJian.OpenFile()) != null)
                {
                    length = (int)photo.Length;
                    byte[] byts = new byte[length];
                    photo.Read(byts, 0, byts.Length);
                    lstBytes.Add(byts);
                    BitmapImage images = new BitmapImage(new Uri(ofdWenJian.FileName));
                    img_photo.Source = images;
                    txt_Load.Text = ofdWenJian.FileName;
                }
            }
            else
            {
                MessageBox.Show("图片为空！");
            }
        }
        /// <summary>
        /// 清空图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Clean_Click(object sender, RoutedEventArgs e)
        {
            lstBytes.Clear();
            img_photo.Source = null;
            txt_Load.Text = string.Empty;
        }
        /// <summary>
        /// 验证邮件正确性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txt_Email_LostFocus(object sender, RoutedEventArgs e)
        {
            string strEmail = txt_Email.Text.Trim();
            ////使用正则表达式判断是否匹配    
            if (!Regex.IsMatch(strEmail, @"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"))
            {
                MessageBox.Show("Email地址有误，请重新输入！", "系统提示", MessageBoxButton.OKCancel, MessageBoxImage.Error);
                txt_Email.Text = "";
            }
        }
    }
}
